package com.family.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.family.model.*;
import com.family.model.result.ResultModel;
import com.family.model.result.StateCode;
import com.family.network.HttpRequest;
import com.family.service.*;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping(value = "/user")
public class UserController {
    private UserService userService;
    private NameService nameService;
    private GenerationService generationService;
    private WechatService wechatService;
    private RelationshipService relationshipService;

    @SuppressWarnings("SpringJavaAutowiringInspection")
    @Autowired
    public void setNameService(NameService nameService) {
        this.nameService = nameService;
    }

    @SuppressWarnings("SpringJavaAutowiringInspection")
    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    @SuppressWarnings("SpringJavaAutowiringInspection")
    @Autowired
    public void setGenerationService(GenerationService generationService) {
        this.generationService = generationService;
    }

    @SuppressWarnings("SpringJavaAutowiringInspection")
    @Autowired
    public void setWechatService(WechatService wechatService) {
        this.wechatService = wechatService;
    }

    @SuppressWarnings("SpringJavaAutowiringInspection")
    @Autowired
    public void setRelationshipService(RelationshipService relationshipService) {
        this.relationshipService = relationshipService;
    }

    /**
     * 登录
     *
     * @param wechatId
     * @return
     */
    @RequestMapping(value = "/login.do", method = {RequestMethod.GET, RequestMethod.POST})
    public ResultModel<User> login(String wechatId) {
        ResultModel<User> resultModel = new ResultModel();
        User userModel = userService.getUserByWechatId(wechatId);
        if (userModel != null) {
            resultModel.setData(userModel);
        } else if ("".equals(wechatId) || wechatId.length() < 10) {
            resultModel.setPrompt("用户不存在");
            resultModel.setStateCode(StateCode.OTHER_ERROR);
        } else {
            userModel = new User();
            userModel.setWechatId(wechatId);
            userService.addUser(userModel);
            resultModel.setData(userModel);
        }
        return resultModel;
    }

    /**
     * 打开小程序，传入微信信息，返回用户信息
     *
     * @return
     */
    @RequestMapping(value = "/addWechatInfo.do", method = {RequestMethod.GET, RequestMethod.POST})
    public ResultModel<WechatInfo> addWechatInfo(String wechatToken, boolean isWechatToken, String nickName, int gender, String city, String province, String country, String avatarUrl) {
        String wechatId = null;
        if (isWechatToken) {
            HashMap<String, String> params = new HashMap<>();
            params.put("appid", "wxafa6c364e82f2523");
            params.put("secret", "a9a12e4fd079165052e4261f702e7f33");
            params.put("grant_type", "authorization_code");
            params.put("js_code", wechatToken);
            String response = HttpRequest.httpGet("https://api.weixin.qq.com/sns/jscode2session", params);

            if (response != null) {
                JSONObject robject = JSON.parseObject(response);
                wechatId = robject.getString("openid");
            } else {
                return null;
            }
        } else {
            wechatId = wechatToken;
        }
        ResultModel<WechatInfo> resultModel = new ResultModel();
        if (wechatId == null || wechatId.trim().length() < 1) {
            resultModel.setStateCode(StateCode.PARAMS_ERROR);
            resultModel.setPrompt("微信用户不存在");
            return resultModel;
        }

        WechatInfo wechatInfo = wechatService.queryWechatByToken(wechatId);
        if (wechatInfo == null) {
            wechatInfo = new WechatInfo();
        }
        wechatInfo.setWechatToken(wechatId);
        wechatInfo.setNickName(nickName);
        wechatInfo.setGender(gender);
        wechatInfo.setCity(city);
        wechatInfo.setProvince(province);
        wechatInfo.setCountry(country);
        wechatInfo.setAvatarUrl(avatarUrl);
        wechatService.addOrUpdateWechatInfo(wechatInfo);
        resultModel.setData(wechatInfo);
        return resultModel;
    }


    /**
     * 添加用户名称
     *
     * @param userId
     * @param wechatId     微信唯一id
     * @param addUserId    添加者id
     * @param realName     真实名称
     * @param nameId       姓id
     * @param generationId 字辈id 可能为null
     * @param gender
     * @param shipId       关系
     * @return
     */
    @RequestMapping(value = "/updateUserInfo.do", method = {RequestMethod.POST, RequestMethod.GET})
    public ResultModel<User> updateUser(int userId, String wechatId, int addUserId, String realName, int nameId, int generationId, int gender, int shipId) {
        User addUser = userService.getUserById(addUserId);
        Name name = nameService.getNameById(nameId);
        Generation generation = generationService.queryGenerationById(generationId);
        User user;
        if (userId == addUserId) {
            user = addUser.clone();
        } else {
            user = userService.getUserById(userId);
            if (user == null) {
                user = new User();
            }
        }
        user.setAddUser(addUser);
        user.setGender(gender);
        user.setRealName(realName);
        user.setWechatId(wechatId);
        user.setName(name);
        user.setGeneration(generation);
        if (user.getId() > 0) {
            userService.updateUser(user);
        } else {
            user = userService.addUser(user);
        }
        RelationShipState relationShipState = relationshipService.queryRelationshipById(shipId);
        if (relationShipState != null) {
            Relationship ship = new Relationship();
            ship.setUser(addUser);
            ship.setToUser(user);
            ship.setRelationShip(relationShipState);
            relationshipService.insertRelationship(addUser, ship);
        }
        ResultModel<User> resultModel = new ResultModel<>();
        resultModel.setData(user);
        return resultModel;
    }

    /**
     * 更新用户关系
     *
     * @param userId
     * @param relationships
     * @return
     */
    @RequestMapping(value = "/updateRelationship.do", method = {RequestMethod.POST, RequestMethod.GET})
    public ResultModel<User> updateRelationship(int userId, List<Relationship> relationships) {
        User user = userService.getUserById(userId);
        ResultModel<User> resultModel = new ResultModel<>();
        if (user == null) {
            resultModel.setPrompt("用户不存在");
            resultModel.setStateCode(StateCode.OTHER_ERROR);
        } else {
            resultModel.setData(user);
        }
        return resultModel;
    }

    /**
     * 查询用户添加的所有用户
     *
     * @param userId
     * @return
     */
    @RequestMapping(value = "/queryUsersByAddedId.do", method = {RequestMethod.GET, RequestMethod.POST})
    public ResultModel<List<User>> queryUsersById(int userId) {
        ResultModel<List<User>> resultModel = new ResultModel<>();
        resultModel.setData(userService.queryUsersById(userId));
        return resultModel;
    }


    /**
     * 根据名字查询同名用户
     *
     * @param name
     * @param status 是否被认证 0:all,1:已经认证，2:未认证
     * @return
     */
    @RequestMapping(value = "/queryUsersByName.do", method = {RequestMethod.GET, RequestMethod.POST})
    public ResultModel<List<User>> queryUsersByName(String name, int status) {
        ResultModel<List<User>> resultModel = new ResultModel<>();
        resultModel.setData(userService.queryUsersByName(name, status));
        return resultModel;
    }

    @RequestMapping(value = "/queryLikeName.do", method = {RequestMethod.GET, RequestMethod.POST})
    public ResultModel<PageInfo<User>> queryUserLikeName(String name, int pageIndex, int pageSize) {
        ResultModel<PageInfo<User>> resultModel = new ResultModel<>();
        PageInfo<User> pageMode = userService.queryUsersLikeName(name, pageIndex, pageSize);
        resultModel.setData(pageMode);
        resultModel.setStateCode(StateCode.RESULT_OK);
        return resultModel;
    }

}
